/* eslint-disable prettier/prettier */
import React, { useState, useEffect } from 'react';
import s from './style.module.css';
import i from '@/index.module.css';
import cn from 'classnames';
import { Link, useHistory, useLocation } from 'react-router-dom';
import BreadCrumbBox from '@/components/BreadCrumb';
import ms from 'ms';
import {
  Button,
  Table,
  Input,
  Switch,
  Tooltip,
  Pagination,
  Confirm,
  Dialog, 
  Message,
  Progress,
  Loading,
} from '@knownsec/react-component';
import { filterNull } from '@/utils';
import { getTaskGroup, delTaskGroup, changeTaskStatus, getGroupTotal,putGroupRescan } from '~/API';
import scheduled from '@/assets/svg/scheduled.svg';
import queued from '@/assets/svg/queued.svg';
import processing from '@/assets/svg/processing.svg';
import end from '@/assets/svg/end.svg';
import moment from 'moment';
import Icon from '@/assets/icon';
import CopyText from '@/components/copy'
import SentAlert from '@/components/SentAlert'

const option = [
  { label: '安全事件', value: 'securityEvent' },
  { label: 'Web漏洞', value: 'vul' },
  { label: '可用性', value: 'availability' },
  // { label: '内容', value: 'target_info' },
  { label: '风险外链', value: 'risk_link' },
  { label: '篡改', value: 'change_check' },

];

function formatTime(st, et, type) {
  let dateType = 'YYYY-MM-DD HH:mm';
  if (type) {
    dateType = 'HH:mm';
  }
  if (!st && !et) {
    return '任意时间段';
  } else {
    if(!type){
      st = st ? moment(st).format(dateType) : '-';
      et = et ? moment(et).format(dateType) : '-';
    }
    return st + '至' + et;
  }
}

function TaskGroup() {
  const history = useHistory();
  const prefilter = new URLSearchParams(useLocation().search).get('filter')
  const filter = prefilter?JSON.parse(prefilter) || {}:{}
  const arr = [
    { link: '', name: '任务管理' },
    { link: '', name: '任务组', active: true },
  ];
  const [refe, setRef] = useState(false);
  const [loading, setLoading] = useState(false);
  const [username, setUserName] = useState(filter.username || '');
  const [target_group_name, setTargetName] = useState(filter.target_group_name || '');
  const [target_url, setUrl] = useState(filter.target_url || '');
  const [dataList, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [dataCount, setTotalData] = useState({ target_count: 0, target_group_count: 0 });
  const [page, setPage] = useState({ page:  filter.page||1, limit: filter.limit||10 });
  const [selectIds, setSelTable] = useState([]);
  const [isDowning, setIsDowning] = useState(false);
  const [upVisible, setUpVisible] = useState('');
  const [percent, setPercent] = useState(0);
  const [sendData, setSendData] = useState(null)

  //批量导出
  const showDialog = async () => {
    Confirm({
      pro: true,
      title: '提示',
      message: <div className="confirmbox">确认导出所选业务组报告？</div>,
      onconfirm: async () => {
        setIsDowning(true);
        let timer = null;
        let per = 0;
        timer = setInterval(() => {
          if (per > 87) {
            clearInterval(timer);
          } else {
            const d = Math.ceil(Math.random() * 10);
            per += d;
            setPercent((x) => (x += d));
          }
        }, 1000);
        let params = {};
        let pace = {};
        let setIn = null;
        params = { target_ids: selectIds };
        await postReport(params);
        setUpVisible('压缩');
        params = { type: 'progress' };
        setIn = setInterval(async () => {
          pace = await postReport(params);
          if (pace.status == 1) {
            clearInterval(timer);
            clearInterval(setIn);
            setPercent(100);
            setUpVisible('');
            await getReportAll();
            setSelTable([]);
            setRef(!refe);
            setPercent(0);
            setIsDowning(false);
          }
        }, 2000);
      },
      oncancel: () => {},
    });
  };
  //周期时间转换
  const timeUnit=(value)=>{
    const nv = value * 1000;
    const freq = ms(nv);
    let unit = value ? freq.replace(/\d*/, '') : 'd';
    let num = parseInt(freq.replace(/[a-zA-Z]/, ''), 10);
    if (nv % ms('30d') === 0) {
      unit = '月';
      num = nv / ms('30d');
    } else if (nv % ms('1w') === 0) {
      unit = '周';
      num = nv / ms('1w');
    } else if (nv % ms('1d') === 0) {
        unit = '天';
        num = nv / ms('1d');
    }else if (nv % ms('1h') === 0) {
        unit = '小时';
        num = nv / ms('1h');
    }else{
        unit = '分钟';
        num = nv / ms('1m');  
    }
    let text= `${num+unit}一次`
    return text
  }
  const columns = [
    {
      key: 'target_group_name',
      dataIndex: 'target_group_name',
      title: '任务组名称',
      className: 'w114',
      render: (e)=>{
        return <Tooltip
        overlay={<p>任务组名称：<CopyText text={e}/></p>}
        placement="topLeft"
      >
        <span>{e}</span>
        </Tooltip>
         
      }
    },
    {
      key: 'target_count',
      dataIndex: 'target_count',
      title: '业务系统数',
      className: 'w114',
      render: (value) => (value ? value : '0'),
    },
    {
        key: 'task_config',
        dataIndex: 'task_config',
        title: '任务类型',
        className: 'w114',
        render: (e,row) => {
        const text=e.is_periodic?'周期任务':'单次任务'
            return <div className={s.typeDiv}>
                <Icon active={e.is_periodic?'cycle':'once'}/>
                <span className={s.itemSpan}>{text}</span>
            </div>
        },
    },
    {
      key: 'task_config2',
      dataIndex: 'task_config',
      title: '任务状态',
      render: (value, _data) =>
        value.is_periodic ? (
          <Tooltip
            className={s.ml100}
            overlay={
              <>
                <p>状态：{_data.enable ? '已启用' : '已禁用'}</p>
                <p>
                  监控时间：{formatTime(value.start_at, value.end_at)}
                </p>
                <p>
                  每天可执行时间段：
                  {formatTime(value.scan_period_start_time, value.scan_period_end_time, 1)}
                </p>
                {option.map((item, index) => {
                  return (
                    <p key={index}>
                      <span className={s.timeKey}>{item.label}</span>：
                      {value[item.value].is_disabled
                        ? '-'
                        : value[item.value] && value[item.value].seconds
                        ?timeUnit(value[item.value].seconds)
                        : '-'}
                    </p>
                  );
                })}
              </>
            }
            placement={'top'}
          >
            <Switch
              pro
              id={_data.id}
              onChange={switchChange}
              checked={_data.enable}
            />
          </Tooltip>
        ) : (value.promptly?<p>
           立即执行
          </p>:
            <p>
            {value.start_at ? moment(value.start_at).format('YYYY-MM-DD HH:mm') : '-'}
            开始执行
          </p>
        ),
    },
    {
      key: 'status',
      dataIndex: 'status',
      title: '监测情况',
      render: (value) => (
        <Tooltip
          className={s.ml100}
          overlay={`等待调度：${value.TS_SCHEDULED || 0}；等待扫描：
        ${value.TS_QUEUED || 0}；正在执行：${value.TS_PROCESSING || 0}；扫描结束：${
            value.TS_COMPLETED || 0
          }`}
          placement={'top'}
        >
          <div className={s.tipBox}>
            <img className={s.statusImg} src={scheduled} alt="" />
            <span className={s.numSpan}>{value.TS_SCHEDULED || 0}</span>
            <img className={s.statusImg} src={queued} alt="" />
            <span className={s.numSpan}>
            {value.TS_QUEUED || 0}
            </span>
            <img className={s.statusImg} src={processing} alt="" />
            <span className={s.numSpan}>
            {value.TS_PROCESSING || 0}
            </span>
            <img className={s.statusImg} src={end} alt="" />
            <span className={s.numSpan}>
            {value.TS_COMPLETED || 0}
            </span>
          </div>
        </Tooltip>
      ),
    },
    {
      key: 'username',
      dataIndex: 'username',
      title: '所属用户',
      className: 'w114',
    },
    {
      key: 'option',
      dataIndex: 'option',
      title: '操作',
      className: 'bwidth',
      render: (value, _data) => (
        <>
          <Link
            className={s.linkStyle}
            to={{
              pathname: '/form_page',
              search: `id=${_data.id}&type=group&back=${prefilter}`,
            }}
          >
            <span className={s.itemSpan}>编辑</span>
          </Link>
          <Link className={cn(s.linkStyle,   s.linkStyle2)} to={{ pathname: `/task_list`, search: `taskname=${encodeURI(_data.target_group_name)}` }}>
            任务队列
          </Link>
          <a className={s.linkStyle} href={`/#/task_info/id=${_data.target_group_id}`} target='_blank'>
            监测详情
          </a>
        </>
      ),
    },
  ];
  const goForm = () => {
    history.push({ pathname: '/form_page', search: `back=${prefilter}&type=groupadd` });
  };
  function switchChange(bool, item) {
    if (item && item.currentTarget.id){
      setLoading(true)
      changeTaskStatus({
        data: { enable: bool },
        id: item.currentTarget.id,
      }).then((res) => {
        setLoading(false)
        if (res.status == 'success') {
          Message.show({
            pro: true,
            type: 'success',
            message: '操作成功',
            showClose: false,
          });
          getList();
        }
      }).catch((res)=>{
        setLoading(false)
        Message.show({
            className:s.w_25,
            pro: true,
            type: 'error',
            message: res.data.task_config||Object.values(res.data)[0],
            showClose: false,
          });
      });

    } else {
      Message.show({
        pro: true,
        type: 'error',
        message: '请稍后重试',
        showClose: false,
      });
    }
  }
  function getsum() {
    getGroupTotal().then((res) => {
      if (res.status == 'success') {
        setTotalData(res.data);
      }
    });
  }
  function getList(p) {
    const data = {
      username: username,
      target_group_name: target_group_name,
      target_url: target_url,
      page: page.page,
      limit: page.limit,
    };
    if (p) {
      data.page = 1;
      if (p.page) {
        data.page = p.page;
        data.limit = p.limit;
      }
      if (p.val) {
        data[p.val] = '';
      }
      setPage({ page: data.page, limit: data.limit });
    }
    const backparams = JSON.stringify(filterNull(data));
    const searchString = 'filter='+encodeURI(backparams)
    history.replace(`/task_group?${searchString}`)
    setLoading(true)
    setRef(!refe)
    setSelTable([])
    getTaskGroup(data).then((res) => {
      setLoading(false)
      if (res.status == 'success') {
        if (res.data && res?.data?.data?.length) {
          let data = res.data.data.map((item) => {
            item.id = item.target_group_id;
            return item;
          });
          res.data.data = data;
        }
        setData(res.data?.data || []);
        setTotal(res.data?.total || 0)
      }
    });
  }
  function onSearchChange(data) {
    setPage(data);
    getList(data);
  }
  function delGroups() {
    Confirm({
      title: '确认提示',
      pro: true,
      message: <div className="confirmbox">确认要删除选中的任务组吗？</div>,
      onconfirm: () => {
        // selectIds
        delTaskGroup({ target_group_ids: selectIds }).then((res) => {
          if (res.status == 'success') {
            setSelTable([]);
            setRef(!refe);
            getList(1);
            getsum();
            Message.show({
              pro: true,
              type: 'success',
              message: '删除任务组成功',
              showClose: false,
            });
          }
        });
      },
      oncancel: () => {},
    });
  }
  const taskCreate = async ({ id }) => {
    let selTable_ = id ? id : selectIds;
    let closeId=[]
    dataList.forEach((e)=>{
        if(selTable_.includes(e.id)){
            if(!e.enable&&e.task_config.is_periodic){
                closeId.push(e.id)
            }
        }
    })
    const text=closeId[0]?'选中任务组存在处于监测关闭状态，下发立即检测将开启任务组监测状态并重置您所选任务组周期时间，您确认要立即检测？':'本次检测将重置您设置的周期性监测任务时间，确认要立即检测选中的业务系统吗？'
    Confirm({
      title: '提示',
      pro: true,
      className:s.confirmOutbox,
      message: (<div className={s.confirmbox}>{text}</div>),
      onconfirm: async () => {
        if(closeId[0]){
            const pArr=[]
            closeId.forEach((id)=>{
                pArr.push(changeTaskStatus({
                    data: { enable:true },
                    id,
                }))
            })
           const resP= await Promise.all(pArr).catch((e)=>{return 'err'})
           if(resP==='err'){
            Message.show({
                pro: true,
                showClose: false,
                type: 'error',
                message: '下发失败',
            });
            return false
           }
        }
        const res = await putGroupRescan({ target_group_ids: selTable_ }).catch((e)=>{return e});
        getList();
        if (res.status === 'success') {
          Message.show({
            pro: true,
            showClose: false,
            type: 'success',
            message: '下发成功',
          });
        }else{
            const data= res.message.map((e)=>{
                return {name:e[0],target:e[1],cause:e[2]};
            })
            setSendData(data)
        }
        setSelTable([]);
        setRef(!refe);
        selTable_ = [];
      },
      oncancel: () => {},
    });
  };
  const changeShow=()=>{
    setSendData(null)
  }
  useEffect(() => {
    getList();
    getsum();
  }, []);
  return (
    <>
      <BreadCrumbBox arr={arr}>
        <div className={s.total}>
          <div className={s.item}>
            <label>任务组数</label>
            <p>{dataCount.target_group_count}</p>
          </div>
          <div className={s.item}>
            <label>业务系统数</label>
            <p>{dataCount.target_count}</p>
          </div>
        </div>
      </BreadCrumbBox>
      <div className={s.content}>
        {/* <Loading show={loading} /> */}
        <div className={s.tablebox}>
          <div className={s.searchBox}>
            <div className={s.searchLeft}>
              <Button className={s.mr20} pro type="primary" onClick={goForm}>
                接入业务系统
              </Button>
            
              {/* 暂时先不做 
              <Button
                pro
                type="default"
                disabled={!selectIds.length || isDowning}
                onClick={showDialog}
              >
                导出报告
              </Button> */}
            </div>
            <div className={s.searchRight}>
              <Input
                pro
                placeholder="搜索所属用户"
                value={username}
                className={cn(s.searchName, 'search-button')}
                search
                onSearch={getList}
                clear
                onChange={(value) => {
                  if (!value.e) {
                    getList({ val: 'username' });
                  }
                  setUserName(value.value);
                }}
              ></Input>
              <Input
                pro
                placeholder="搜索任务组名称"
                value={target_group_name}
                className={cn(s.searchName, 'search-button')}
                search
                onSearch={getList}
                clear
                onChange={(value) => {
                  if (!value.e) {
                    getList({ val: 'target_group_name' });
                  }
                  setTargetName(value.value);
                }}
              ></Input>
              <Input
                pro
                placeholder="搜索业务系统地址"
                value={target_url}
                className={cn(s.searchName, 'search-button last')}
                search
                onSearch={getList}
                clear
                onChange={(value) => {
                  if (!value.e) {
                    getList({ val: 'target_url' });
                  }
                  setUrl(value.value);
                }}
              ></Input>
            </div>
            <div className={s.allDel}>
                <Button type="text" onClick={delGroups}
                disabled={!selectIds.length}>删除</Button>
                <Button
                    disabled={!selectIds.length}
                    onClick={taskCreate}
                    type="text"
                >
                    立即检测
               </Button>
            </div>
            
          </div>
          <Table
            selectable
            refre={refe}
            className={selectIds.length ? 'half-select' : ''}
            columns={columns}
            data={dataList}
            tableLoading={loading}
            loadingLabel=""
            getCheckedList={(e) => {
              setSelTable(e);
            }}
          ></Table>
          {total > 10 && <Pagination
            key={Number(123)}
            className={s.pagination}
            current={page.page}
            showQuickJumper={{ goButton: true }}
            showSizeChanger={true}
            pageSize={page.limit}
            pageSizeOptions={['10', '20', '50']}
            total={total}
            showTotal={(total) => `共${total}条`}
            onChange={(page, size) => {
              onSearchChange({ page, limit: size });
            }}
          />}
        </div>
      </div>
      <Dialog
        className={cn(i.w400)}
        title={'提示'}
        visible={upVisible}
        cancelText=""
        confirmText=""
        // closable={false}
        onhide={() => {
          changeVisible();
        }}
      >
        <div className={i.p20}>
          <p className={cn(i.tac)}>正在进行{upVisible}</p>
          <p className={cn(i.tac)}>进度:{percent}%</p>
          <Progress percent={percent + '%'} className={i.mt10} />
        </div>
      </Dialog>
      <SentAlert data={sendData} type={1} changeShow={changeShow}></SentAlert>
    </>
  );
}

export default TaskGroup;
